import React, { useState, useEffect } from 'react';
import { StyleSheet, View, ScrollView, Alert, KeyboardAvoidingView, Platform } from 'react-native';
import { Button, ProgressBar, SegmentedButtons, Checkbox, TextInput, Chip } from 'react-native-paper';
import { router } from 'expo-router';
import { useAuth } from '@/contexts/AuthContext';
import { ThemedView } from '@/components/ThemedView';
import { ThemedText } from '@/components/ThemedText';
import { Colors } from '@/constants/Colors';
import { useColorScheme } from '@/hooks/useColorScheme';

export default function LifestyleScreen() {
  const colorScheme = useColorScheme();
  const { userInfo, userToken, updateProfile } = useAuth();
  const tintColor = Colors[colorScheme ?? 'light'].tint;

  // 表单状态
  const [maritalStatus, setMaritalStatus] = useState(userInfo?.maritalStatus || '');
  const [hasChildren, setHasChildren] = useState(userInfo?.hasChildren || false);
  const [wantsChildren, setWantsChildren] = useState(userInfo?.wantsChildren || false);
  const [smoking, setSmoking] = useState(userInfo?.smoking || '');
  const [drinking, setDrinking] = useState(userInfo?.drinking || '');
  const [diet, setDiet] = useState(userInfo?.diet || '');
  const [hasPets, setHasPets] = useState(userInfo?.hasPets || false);
  const [petInput, setPetInput] = useState('');
  const [pets, setPets] = useState<string[]>(userInfo?.pets || []);
  const [isLoading, setIsLoading] = useState(false);

  // 如果用户未登录，重定向到登录页面
  useEffect(() => {
    if (!userToken) {
      router.replace('/auth/login');
    }
  }, [userToken]);

  // 添加宠物
  const addPet = () => {
    if (petInput.trim() && !pets.includes(petInput.trim())) {
      setPets([...pets, petInput.trim()]);
      setPetInput('');
    }
  };

  // 移除宠物
  const removePet = (pet: string) => {
    setPets(pets.filter(p => p !== pet));
  };

  // 处理表单提交
  const handleSubmit = async () => {
    // 验证必填字段
    if (!maritalStatus) {
      Alert.alert('提示', '请选择您的婚姻状况');
      return;
    }
    if (!smoking) {
      Alert.alert('提示', '请选择您的吸烟习惯');
      return;
    }
    if (!drinking) {
      Alert.alert('提示', '请选择您的饮酒习惯');
      return;
    }
    if (!diet) {
      Alert.alert('提示', '请选择您的饮食习惯');
      return;
    }

    console.log('开始提交生活方式信息:', { maritalStatus, smoking, drinking, diet });
    setIsLoading(true);
    try {
      // 更新用户生活方式信息
      const success = await updateProfile({
        maritalStatus,
        hasChildren,
        wantsChildren,
        smoking,
        drinking,
        diet,
        hasPets,
        pets
      }, null);

      console.log('更新生活方式信息结果:', success);
      if (success) {
        // 进入下一步 - 使用setTimeout确保导航在UI更新后执行
        console.log('生活方式信息更新成功，准备导航到兴趣爱好页面');
        setTimeout(() => {
          console.log('导航到兴趣爱好页面');
          router.push('/profile-setup/interests' as any);
        }, 1000);
      } else {
        Alert.alert('错误', '更新个人资料失败，请重试');
      }
    } catch (error) {
      console.error('Update profile error:', error);
      Alert.alert('错误', '发生未知错误，请重试');
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <ThemedView style={styles.container}>
      <KeyboardAvoidingView
        behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
        style={styles.keyboardAvoidingView}
      >
        <ScrollView contentContainerStyle={styles.scrollContent}>
          <View style={styles.header}>
            <ThemedText style={styles.title}>生活方式</ThemedText>
            <ThemedText style={styles.subtitle}>
              请告诉我们关于您的生活习惯和家庭状况
            </ThemedText>
          </View>

          <ProgressBar 
            progress={3/6} 
            color={tintColor} 
            style={styles.progressBar} 
          />

          <View style={styles.formContainer}>
            <View style={styles.formGroup}>
              <ThemedText style={styles.label}>婚姻状况</ThemedText>
              <SegmentedButtons
                value={maritalStatus}
                onValueChange={setMaritalStatus}
                buttons={[
                  { value: 'single', label: '单身' },
                  { value: 'divorced', label: '离异' },
                  { value: 'widowed', label: '丧偶' }
                ]}
                style={styles.segmentedButtons}
              />
            </View>

            <View style={styles.formGroup}>
              <ThemedText style={styles.label}>子女情况</ThemedText>
              <View style={styles.checkboxContainer}>
                <Checkbox
                  status={hasChildren ? 'checked' : 'unchecked'}
                  onPress={() => setHasChildren(!hasChildren)}
                  color={tintColor}
                />
                <ThemedText style={styles.checkboxLabel}>我有孩子</ThemedText>
              </View>
              <View style={styles.checkboxContainer}>
                <Checkbox
                  status={wantsChildren ? 'checked' : 'unchecked'}
                  onPress={() => setWantsChildren(!wantsChildren)}
                  color={tintColor}
                />
                <ThemedText style={styles.checkboxLabel}>我想要孩子</ThemedText>
              </View>
            </View>

            <View style={styles.formGroup}>
              <ThemedText style={styles.label}>吸烟习惯</ThemedText>
              <SegmentedButtons
                value={smoking}
                onValueChange={setSmoking}
                buttons={[
                  { value: 'never', label: '不吸烟' },
                  { value: 'occasionally', label: '偶尔吸烟' },
                  { value: 'regularly', label: '经常吸烟' }
                ]}
                style={styles.segmentedButtons}
              />
            </View>

            <View style={styles.formGroup}>
              <ThemedText style={styles.label}>饮酒习惯</ThemedText>
              <SegmentedButtons
                value={drinking}
                onValueChange={setDrinking}
                buttons={[
                  { value: 'never', label: '不饮酒' },
                  { value: 'socially', label: '社交饮酒' },
                  { value: 'regularly', label: '经常饮酒' }
                ]}
                style={styles.segmentedButtons}
              />
            </View>

            <View style={styles.formGroup}>
              <ThemedText style={styles.label}>饮食习惯</ThemedText>
              <SegmentedButtons
                value={diet}
                onValueChange={setDiet}
                buttons={[
                  { value: 'omnivore', label: '无特殊' },
                  { value: 'vegetarian', label: '素食' },
                  { value: 'vegan', label: '纯素' },
                  { value: 'other', label: '其他' }
                ]}
                style={styles.segmentedButtons}
              />
            </View>

            <View style={styles.formGroup}>
              <ThemedText style={styles.label}>宠物情况</ThemedText>
              <View style={styles.checkboxContainer}>
                <Checkbox
                  status={hasPets ? 'checked' : 'unchecked'}
                  onPress={() => setHasPets(!hasPets)}
                  color={tintColor}
                />
                <ThemedText style={styles.checkboxLabel}>我养宠物</ThemedText>
              </View>

              {hasPets && (
                <View style={styles.petsContainer}>
                  <ThemedText style={styles.subLabel}>您养哪些宠物？</ThemedText>
                  <View style={styles.inputWithButton}>
                    <TextInput
                      value={petInput}
                      onChangeText={setPetInput}
                      mode="outlined"
                      placeholder="例如：猫、狗、兔子"
                      style={styles.petInput}
                      outlineColor="#CCCCCC"
                      activeOutlineColor={tintColor}
                      theme={{ roundness: 10 }}
                      onSubmitEditing={addPet}
                    />
                    <Button
                      mode="contained"
                      onPress={addPet}
                      style={styles.addButton}
                      theme={{ roundness: 10 }}
                    >
                      添加
                    </Button>
                  </View>

                  <View style={styles.chipContainer}>
                    {pets.map((pet, index) => (
                      <Chip
                        key={index}
                        onClose={() => removePet(pet)}
                        style={styles.chip}
                        textStyle={styles.chipText}
                      >
                        {pet}
                      </Chip>
                    ))}
                  </View>
                </View>
              )}
            </View>
          </View>

          <View style={styles.buttonContainer}>
            <Button
              mode="contained"
              onPress={handleSubmit}
              style={styles.button}
              labelStyle={styles.buttonText}
              loading={isLoading}
              disabled={isLoading}
              theme={{ roundness: 10 }}
            >
              下一步
            </Button>

            <Button
              mode="outlined"
              onPress={() => router.push('/profile-setup/appearance')}
              style={[styles.button, styles.backButton]}
              labelStyle={styles.backButtonText}
              theme={{ roundness: 10 }}
            >
              返回
            </Button>
          </View>
        </ScrollView>
      </KeyboardAvoidingView>
    </ThemedView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  keyboardAvoidingView: {
    flex: 1,
  },
  scrollContent: {
    flexGrow: 1,
    padding: 20,
  },
  header: {
    marginTop: 40,
    marginBottom: 30,
    alignItems: 'center',
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 10,
    textAlign: 'center',
  },
  subtitle: {
    fontSize: 16,
    textAlign: 'center',
    opacity: 0.7,
    marginBottom: 10,
  },
  progressBar: {
    height: 8,
    borderRadius: 4,
    marginBottom: 30,
  },
  formContainer: {
    marginBottom: 30,
  },
  formGroup: {
    marginBottom: 25,
  },
  label: {
    fontSize: 16,
    marginBottom: 8,
    fontWeight: '500',
  },
  subLabel: {
    fontSize: 14,
    marginBottom: 8,
  },
  segmentedButtons: {
    marginBottom: 10,
  },
  checkboxContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 10,
  },
  checkboxLabel: {
    marginLeft: 8,
    fontSize: 16,
  },
  petsContainer: {
    marginTop: 10,
    marginLeft: 30,
  },
  inputWithButton: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 10,
  },
  petInput: {
    flex: 1,
    backgroundColor: 'transparent',
  },
  addButton: {
    marginLeft: 10,
  },
  chipContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    marginTop: 5,
  },
  chip: {
    margin: 4,
  },
  chipText: {
    fontSize: 14,
  },
  buttonContainer: {
    marginTop: 'auto',
    marginBottom: 20,
  },
  button: {
    marginBottom: 15,
    paddingVertical: 8,
  },
  buttonText: {
    fontSize: 16,
    fontWeight: 'bold',
  },
  backButton: {
    borderColor: '#ccc',
  },
  backButtonText: {
    fontSize: 16,
  },
});
